"""
数据库元数据模型
用于描述数据库表结构和列信息的通用模型
"""

from typing import Optional, List, Dict, Any
from enum import Enum
from pydantic import BaseModel, Field
from datetime import datetime


class ColumnType(str, Enum):
    """列数据类型枚举"""
    STRING = "string"
    INTEGER = "integer"
    FLOAT = "float"
    BOOLEAN = "boolean"
    DATETIME = "datetime"
    DATE = "date"
    TIME = "time"
    JSON = "json"
    UUID = "uuid"
    ENUM = "enum"
    BINARY = "binary"
    TEXT = "text"
    ARRAY = "array"
    UNKNOWN = "unknown"


class ColumnConstraint(str, Enum):
    """列约束类型枚举"""
    PRIMARY_KEY = "primary_key"
    FOREIGN_KEY = "foreign_key"
    UNIQUE = "unique"
    NOT_NULL = "not_null"
    INDEXED = "indexed"
    AUTO_INCREMENT = "auto_increment"
    DEFAULT = "default"


class ColumnMetadata(BaseModel):
    """列元数据模型"""
    name: str = Field(..., description="列名")
    type: ColumnType = Field(..., description="数据类型")
    python_type: str = Field(..., description="Python类型")
    nullable: bool = Field(..., description="是否可为空")
    default: Optional[Any] = Field(None, description="默认值")
    max_length: Optional[int] = Field(None, description="最大长度（适用于字符串类型）")
    constraints: List[ColumnConstraint] = Field(default_factory=list, description="约束列表")
    foreign_key: Optional[str] = Field(None, description="外键信息")
    comment: Optional[str] = Field(None, description="列注释")
    is_primary: bool = Field(False, description="是否为主键")


class TableMetadata(BaseModel):
    """表元数据模型"""
    name: str = Field(..., description="表名")
    schema_name: Optional[str] = Field(None, description="模式名")
    columns: List[ColumnMetadata] = Field(..., description="列列表")
    primary_keys: List[str] = Field(default_factory=list, description="主键列名列表")
    indexes: List[Dict[str, Any]] = Field(default_factory=list, description="索引信息")
    comment: Optional[str] = Field(None, description="表注释")
    row_count: Optional[int] = Field(None, description="行数统计")


class DatabaseMetadataResponse(BaseModel):
    """数据库元数据响应模型"""
    tables: List[TableMetadata] = Field(..., description="所有表信息")
    total_tables: int = Field(..., description="表总数")


class TableStats(BaseModel):
    """表统计信息"""
    table_name: str = Field(..., description="表名")
    row_count: int = Field(..., description="行数")
    size_mb: float = Field(..., description="表大小（MB）")
    last_analyzed: Optional[datetime] = Field(None, description="最后分析时间")
